using System;
using System.Collections.Generic;
using System.Text;
using Emlyn.Common.Tools.LayerInterfaces;

namespace Emlyn.Common.Tools.BusinessLayer
{
    public class BaseMod<T, TKey, TDataLayer>
        where T: BaseItem
        where TDataLayer: IBaseDataLayer<T, TKey>
    {
        protected TDataLayer _dl;

        public BaseMod(TDataLayer adl)
        {
            if (adl == null)
                throw new ArgumentNullException("adl");

            _dl = adl;
        }

        public void Save(T aInstance)
        {
            if (aInstance.IsNew)
            {
                _dl.Insert(aInstance);
                aInstance.IsNew = false;
            }
            else
            {
                _dl.Update(aInstance);
            }
        }

        public void Save(IList<T> aInstanceList)
        {
            foreach (T lInstance in aInstanceList)
            {
                Save(lInstance);
            }
        }

        public void Delete(T aInstance)
        {
            if (!aInstance.IsNew)
            {
                _dl.Delete(_dl.GetKey(aInstance));
                aInstance.IsNew = true;
            }
        }

        public void Delete(IList<T> aInstanceList)
        {
            foreach (T lInstance in aInstanceList)
            {
                Delete(lInstance);
            }
        }
    }
}
